<template>
  <PageLayout full safe-area="none">
    <template #header>
      <HeaderLayout center>{{ $t('Discovery.Navigate.Title') }}</HeaderLayout>
    </template>
    <PageLayout safe-area="none">
      <!-- 内容 -->
      <scroll-view
        id="scroll-view"
        class="banner-img-box"
        scroll-y
        upper-threshold="5"
        :scroll-top="scrollTop"
        @scrolltolower="loadMoreData"
        @scroll="scrollEvent"
      >
        <!-- 搜索框 -->
        <view class="search-box" @click="jumpSearch" v-if="!isSkeleton">
          <view class="search-input">{{ hotWordsArray[hotWordsIndex] }}</view>
          <image class="search-icon" :src="'/static/Search.png'"></image>
        </view>
        <view class="search-box skeleton-item cover-skeleton" v-else></view>
        <!-- 活动 -->
        <view class="more-active-box" :class="fixedFlag === true ? 'isFixed' : ''" v-if="!isSkeleton">
          <!-- <view class="active-box" :class="{ active: selectedIndex === 0 }" @click="changeTab(0)">
            <view class="active-title">{{ $t('Discovery.TabBar.NewProduct.Text') }}</view>
            <view class="tab-line"></view>
          </view>
          <view class="active-box" :class="{ active: selectedIndex === 1 }" @click="changeTab(1)">
            <view class="active-title">{{ $t('Discovery.TabBar.PlayApp.Text') }}</view>
            <view class="tab-line"></view>
          </view>
          <view class="active-box" :class="{ active: selectedIndex === 2 }" @click="changeTab(2)">
            <view class="active-title">{{ $t('Discovery.TabBar.HotActive.Text') }}</view>
            <view class="tab-line"></view>
          </view> -->
          <view
            class="active-box"
            v-for="(items, index) in showList"
            :key="index"
            :class="{ active: selectedIndex === index }"
          >
            <view class="active-title" @click="changeTab(index, items)">{{ items.name }}</view>
            <view class="tab-line"></view>
          </view>
        </view>
        <view class="search-box skeleton-item cover-skeleton" v-else></view>
        <!--内容-->
        <view v-if="!isSkeleton">
          <!--数据不为空-->
          <view
            v-if="dataArray.length > 0"
            v-for="(data, index) in dataArray"
            :key="data.id"
            class="banner-img"
            @click="openArticle(data)"
          >
            <alt-picture class="bg-img" mode="aspectFill" :src="data.coverpic" />
            <view class="bottom-label">
              <view class="title">{{ wordLimit(data.title) }}</view>
              <view class="read-count"
                >{{ handleViewTotal(data.viewTotal) }}{{ $t('Discovery.Article.Read.Text') }}</view
              >
            </view>
          </view>
          <!--数据为空-->
          <view v-else class="no-data">
            <view class="no-data-view">
              <image :src="netconfig.ASSETS_IMGURL + 'img_message_empty.png'" class="icon" />
              <view class="text">{{ $t('Discovery.Empty.Article.Text') }}</view>
            </view>
          </view>
        </view>
        <view v-else>
          <view class="banner-img skeleton-item cover-skeleton" v-for="item in [1, 2, 3]" :key="item"></view>
        </view>
        <!--底部提示文案-->
        <view class="bottom-tip" v-if="dataArray.length >= 3" @click="scrollToTop">
          <view class="left-tip">{{ $t('Discovery.Bottom.Tips.Text') }}，</view>
          <view class="right-tip">
            <view class="left-tip">{{ $t('Discovery.Bottom.Tips.Button') }}</view>
            <image class="top-arrow" src="/static/ic_up.png"></image>
            <view class="line"></view>
          </view>
        </view>
        <view class="empty-box"></view>
      </scroll-view>
    </PageLayout>
  </PageLayout>
</template>

<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'

import loginHelper from '@/pluginHelper/login'
import { getHcConfigList, getHcConfigDetail, getHotHcConfigList } from '../../../api/content'
import type { HCConfigInfoModel } from '../../../api/content'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { useEnvStore } from '@/store/env'
import { toPage } from '@/utils/mpHelper'
import { cloneDeep } from 'lodash'
import { useAuthStore } from '@/store/auth'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { safeTrack } from '@/dataReport/dataReportUtil'
import netconfig from '@/config/netconfig'

const envStore = useEnvStore()
const authStore = useAuthStore()
// 吸顶高度
const headerHeight = computed(() => `${envStore.titleBarHeight - 10}px`)

const hasData = computed(() => {
  return dataArray.value.length > 0
})
// 骨架屏 未加载出来数据时显示
const isSkeleton = ref(true)
const selectedIndex = ref(0)
const hotWordTimer = ref(setInterval(() => {}))

// 新品来袭
const newProductsArray = ref<HCConfigInfoModel[]>([])
let newProductsPage = 1
const newProductHasMore = ref(false)
// 玩转晶御
const playArroundArray = ref<HCConfigInfoModel[]>([])
let playArroundPage = 1
const playArroundHasMore = ref(false)
// 热门活动
const hotActivityArray = ref<HCConfigInfoModel[]>([])
let hotActivityPage = 1
const hotActivityHasMore = ref(false)

let pageSize = 5
const dataArray = ref<HCConfigInfoModel[]>([])

const fixedFlag = ref(false)

const pageArray = [newProductsPage, playArroundPage, hotActivityPage]

const scrollTop = ref(0)
const old = ref({
  scrollTop: 0,
})

const hotWordsArray = ref(['如何共享家电'])
const hotWordsIndex = ref(0)
/**
 * Tab组件生命周期
 */
defineExpose({
  onPageLoad,
  onActive,
})
function onPageLoad(query?: Record<string, any>) {}
function onActive() {
  getConfigInit()
  getHotConfigData()
}

/**
 * 获取搜索推荐热词列表
 */
async function getHotConfigData() {
  let res = await getHotHcConfigList()
  if (res.code === 0) {
    clearInterval(hotWordTimer.value)
    if (res.data && res.data[0].search_recommendation) {
      hotWordsArray.value.splice(0, hotWordsArray.value.length)
      hotWordsArray.value = res.data[0].search_recommendation
      hotWordTimer.value = setInterval(() => {
        if (hotWordsIndex.value >= hotWordsArray.value.length - 1) {
          hotWordsIndex.value = 0
        } else {
          hotWordsIndex.value++
        }
      }, 3000)
    }
  }
}
/**切换tab */
function changeTab(index: number, items: { icon: string; name: string }) {
  let tab_key: string | undefined
  // 埋点
  switch (index) {
    case 0: {
      tab_key = 'Discover.Tab.New.Button.Text'
      break
    }
    case 1: {
      tab_key = 'Discover.Tab.Play.Button.Text'
      break
    }
    case 2: {
      tab_key = 'Discover.Tab.Hot.Button.Text'
      break
    }
  }

  if (index === selectedIndex.value) {
    return
  } else {
    // 未触发置顶 则不回到顶部
    if (old.value.scrollTop < 40) {
    } else {
      // 切换不同的tab 回到顶部
      scrollTop.value = old.value.scrollTop
      nextTick(function () {
        scrollTop.value = 41
      })
    }
  }
  selectedIndex.value = index

  trackEvent('switch_discovery_tab', { tab_name: items.name }, TrackType.ApplianceDetail, tab_key)

  detailDataArray(index)
  // getConfigData(false, index)
}

/**
 * 页面加载
 */
onLoad((options) => {})
onShow(() => {})

/**
 * 获取内容数据
 * @param type
 * @param pullupFlag
 */
async function getConfigData(pullupFlag: boolean, type?: number) {
  if (pullupFlag) {
    // 上拉加载
    let page = pageArray[type as number]
    page = page + 1
    let res = await getHcConfigList(type as number, pageArray[selectedIndex.value], pageSize)
    if (res.code === 0) {
      handlePullUpData(res)
    }
  } else {
    let res = await getHcConfigList(type as number, pageArray[selectedIndex.value], pageSize)
    if (res.code === 0) {
      isSkeleton.value = false
      handleResult(res)
    }
  }
}
/**
 * 初始化搜索
 */
const showList = ref<any[]>([])
async function getConfigInit() {
  const res = await getHcConfigList(1, pageSize)
  if (res.code === 0) {
    isSkeleton.value = false
    showList.value = res.data
    if (selectedIndex.value != 0) {
      changeTab(selectedIndex.value || 0, showList.value[selectedIndex.value || 0])
    } else {
      detailDataArray(0)
    }
  }
}
function detailDataArray(initIndex: number) {
  showList.value.map((items, index) => {
    if (initIndex === index) {
      dataArray.value = items.infoList
    }
  })
}
/**
 * 处理初始化数据
 * @param res
 */
function handleResult(res: any) {
  let infoList = filterPublishData(cloneDeep(res.data[0].infoList))
  dataArray.value = []
  dataArray.value = infoList
  switch (selectedIndex.value) {
    case 0:
      newProductsArray.value.splice(0, newProductsArray.value.length)
      newProductHasMore.value = res.data[0].infoList.length === pageSize
      newProductsArray.value = infoList
      break
    case 1:
      playArroundArray.value.splice(0, playArroundArray.value.length)
      playArroundHasMore.value = res.data[0].infoList.length === pageSize
      playArroundArray.value = infoList
      break
    case 2:
      hotActivityArray.value.splice(0, hotActivityArray.value.length)
      hotActivityHasMore.value = res.data[0].infoList.length === pageSize
      hotActivityArray.value = infoList
      break
  }
}

/**
 * 过滤未发布的数据
 */
function filterPublishData(infoList: HCConfigInfoModel[]) {
  if (netconfig.PLUGIN_ENV === 'PCN') {
    return infoList.filter((item) => item.state === '已发布')
  } else {
    return infoList
  }
}

/**
 * 处理分页数据 暂定不分页 代码保留
 * @param res
 */
function handlePullUpData(res: any) {
  switch (selectedIndex.value) {
    case 0:
      newProductHasMore.value = res.data[0].infoList.length === pageSize
      Array.prototype.push.apply(newProductsArray.value, res.data[0].infoList)
      dataArray.value = newProductsArray.value
      break
    case 1:
      playArroundHasMore.value = res.data[0].infoList.length === pageSize
      Array.prototype.push.apply(playArroundArray.value, res.data[0].infoList)
      dataArray.value = playArroundArray.value
      break
    case 2:
      hotActivityHasMore.value = res.data[0].infoList.length === pageSize
      Array.prototype.push.apply(hotActivityArray.value, res.data[0].infoList)
      dataArray.value = hotActivityArray.value
      break
  }
}

/**
 * 上拉加载更多数据 需求暂定不分页
 */
function loadMoreData() {}

/**
 * 处理阅读量
 * @param lookCount
 */
function handleViewTotal(viewTotal: number) {
  let viewTotalString = viewTotal.toString()
  let resultString = viewTotalString.length < 4 ? '0.1' : (Number(viewTotalString) / 10000).toFixed(1)
  return resultString + '万'
}

/**
 *
 * @param content 字符控制
 */
function wordLimit(content: string) {
  if (content.length > 36) {
    let returnContent = content.substring(0, 36)
    returnContent = returnContent + '...'
    return returnContent
  }
  return content
}

/**
 * 监听滑动事件
 * @param detail
 */
function scrollEvent(detail: any) {
  old.value.scrollTop = detail.detail.scrollTop
  if (detail.target.scrollTop > 40) {
    fixedFlag.value = true
  } else {
    fixedFlag.value = false
  }
}
/**
 * 跳转搜索页面
 */
let searchPath = 'pages/discovery/search/search'
async function jumpSearch() {
  searchPath =
    searchPath +
    '?hotWordsArray=' +
    JSON.stringify(hotWordsArray.value) +
    '&hotWords=' +
    hotWordsArray.value[hotWordsIndex.value]
  if (!authStore.isLogin) {
    loginHelper.noCiamIdLogin(undefined, { path: searchPath })
    return
  }
  await toPage(`/${searchPath}`)
}

/**
 * 打开文章详情
 */
function openArticle(model: HCConfigInfoModel) {
  safeTrack(() => {
    trackEvent(
      'check_article_actionhandler',
      { article_id: model.id, article_name: model.title },
      TrackType.ApplianceDetail,
      'Discover.Artile.Select'
    )
  })

  // 去除空格，防止中台配置带空格 跳转出错
  let url = model.url.replace(' ', '')
  uni.navigateTo({
    url: '/pages/webview/webview?url=' + encodeURIComponent(url),
    complete(result) {
      getHcConfigDetail(model.id)
    },
  })
}

/**
 * 滑动到顶部
 */
function scrollToTop() {
  scrollTop.value = 1
  nextTick(function () {
    fixedFlag.value = false
    scrollTop.value = 0
  })
}
</script>

<style lang="less">
@import '@/styles/skeleton.less';
.logo {
  width: 200rpx;
  height: 60rpx;
  background-color: #f4f4f4;
}
.container {
  padding: 0 32rpx;
  font-family: 'PingFang SC';
  font-style: normal;
}
// 搜索框
.search-box {
  position: relative;
  height: 80rpx;
  margin: 0rpx 32rpx 40rpx;
  border-bottom: 1rpx solid #b4b9c3;
  .search-input {
    position: absolute;
    top: 32rpx;
    left: 10rpx;
    font-size: 24rpx;
    letter-spacing: 1rpx;
    font-weight: 400;
    font-size: 28rpx;
    color: #b4b9c3;
  }
  .search-icon {
    width: 36rpx;
    height: 36rpx;
    position: absolute;
    top: 32rpx;
    right: 0;
  }
}
// 活动
.more-active-box {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-bottom: 24rpx;
  .active-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .active-title {
      font-weight: 400;
      font-size: 32rpx;
      color: var(--dark-color);
      opacity: 0.6;
    }
    .tab-line {
      width: 62rpx;
      height: 8rpx;
      margin-top: 8rpx;
      background-color: transparent;
    }
    &.active {
      .active-title {
        font-weight: 500;
        opacity: 1;
      }
      .tab-line {
        background-color: var(--dark-color) !important;
      }
    }
  }
}
// 横幅
.banner-img-box {
  margin-top: 0rpx;
  height: 100%;
  // margin-bottom: 44rpx;
  // padding-bottom: 44rpx;
  .banner-img {
    height: 404rpx;
    margin: 0 32rpx 24rpx;
    position: relative;
    display: block;
    .bg-img {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
    }
    .bottom-label {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      padding: 36rpx 24rpx 16rpx;
      box-sizing: border-box;
      background: linear-gradient(180deg, rgba(9, 8, 6, 0) 0%, #080d09 100%);
      .title {
        font-weight: 500;
        font-size: 40rpx;
        line-height: 56rpx;
        color: #ffffff;
      }
      .read-count {
        font-weight: 400;
        font-size: 20rpx;
        line-height: 28rpx;
        color: #ffffff;
      }
    }
  }
}
.choosed {
  line-height: 40rpx;
  font-family: 'PingFang SC';
  font-style: normal;
  font-weight: 500;
  font-size: 32rpx;
  color: #333333;
}

.isFixed {
  position: fixed;
  top: v-bind(headerHeight);
  z-index: 999;
  display: flex;
  justify-content: space-around;
  align-items: center;
  width: 100%;
  background-color: #ffffff;
  height: 80rpx;
  padding-top: 16rpx;
}

.bottom-tip {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 32rpx 0 44rpx;
  .left-tip {
    font-weight: 400;
    font-size: 24rpx;
    color: var(--dark-color);
    opacity: 0.4;
    line-height: 34rpx;
  }
  .right-tip {
    display: flex;
    align-items: center;
    position: relative;
    .top-arrow {
      width: 22rpx;
      height: 26rpx;
    }
    .line {
      width: 108rpx;
      height: 2rpx;
      background-color: var(--dark-color);
      opacity: 0.4;
      position: absolute;
      bottom: 0;
      right: 8rpx;
    }
  }
}
.empty-box {
  height: 44rpx;
}

.no-data-view {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  .icon {
    width: 275px;
    height: 428rpx;
  }
  .text {
    font-size: 28rpx;
    margin-top: 48rpx;
    color: rgba(45, 55, 70, 1);
  }
}
</style>
